// import React, {useEffect, useRef, useState} from 'react';
// import {createRoot} from 'react-dom/client'
// import styled from 'styled-components'
//
// const MusicContainer = styled.div`
//   position: relative;
//   height: 100%;
//   width: 100%;
//
//   display: flex;
//   align-items: center;
//   justify-content: space-around;
// `
//
// const MusicInfo = styled.div`
//   .coverImg{
//
//   }
//   .songTitle{
//
//   }
//   .artist{
//
//   }
// `
// const coverImg = styled.div``
// const SongTitle = styled.div``
// const Artist = styled.div``
//
//
// const MusicControl = styled.div`
//
// `
//
// const ModeConfig = {
//     "顺序播放":0,
//     "单曲循环":1,
//     "随机播放":2,
// }
// function MusicPlayer(props) {
//     let [nowSong,setNowSong] = useState(0);
//     let [songList,setSongList] = useState([]);
//     let [currentTime,setCurrentTime] = useState(0);
//     let [duration,setDuration] = useState(0);
//     let [au,setAu] = useState(new Audio())
//     let [mode,setMode] = useState("顺序播放")
//     //let au = new Audio();
//     useEffect(()=>{
//         //音频当前时长切换时更换currentTime
//         au.addEventListener("timeupdate",(e)=>{
//             setCurrentTime(au.currentTime)
//         })
//         //音频总时长切换时更换duration
//         au.addEventListener("durationchange",()=>setDuration(au.duration))
//         addSong({
//             title: "again",
//             src:"http://dl.stream.qqmusic.qq.com/C400001LRGpH3S4OZm.m4a?guid=5648128712&vkey=7CC4312353E77C1B4EDDED9B188042AF64927F39B32167D40950905E434BEF8F0E2A41CC09928731004B7B32206394F3AD4A0F067BFE1882&uin=&fromtag=120002",
//             artist: "YUL",
//             imgUrl: "http://y.qq.com/music/photo_new/T002R300x300M000003mWqQk1vNHuU_1.jpg?max_age=2592000",
//         })
//         addSong({
//             title: "失乐园",
//             src:"http://dl.stream.qqmusic.qq.com/C400002b8g102Q7vaO.m4a?guid=5057655460&vkey=1312E4E357DB21CFDC1830E3C1AC3ACC5DCCD237271669416A73D20B2FEA559323DDD5AF8BB4F5D8B55BC0260CDEE36FB9A69BAC8A7DA9A5&uin=&fromtag=120002",
//             artist: "Reol",
//             imgUrl: "//y.qq.com/music/photo_new/T002R300x300M000004eJLOi1je7HU_1.jpg?max_age=2592000",
//         })
//     },[])
//     return (
//         <MusicContainer>
//             <button onClick={()=>play()}>播放</button>
//             <button onClick={()=>pause()}>暂停</button>
//             <button onClick={()=>load()}>load</button>
//             <button onClick={()=>au.currentTime=duration/100*95}>jump</button>
//             <div>{currentTime}/{duration}</div>
//         </MusicContainer>
//     )
//
//     function play(){
//         au.play();
//     }
//     function pause(){
//         au.pause()
//     }
//     function load(){
//         if(songList.length===0) return null;
//         au.src = songList[nowSong].src
//         setNowSong((nowSong+1)%songList.length)
//         au.load()
//         play()
//     }
//     function next(){
//
//     }
//     function prev(){}
//     function changeCurrentTime(){}
//     function clearList(){
//         setSongList([]);
//         setNowSong(-1);
//     }
//     function addSong(params){
//         let song = {
//             title:params?.title || null,
//             artist:params?.artist || null,
//             imgUrl:params?.imgUrl || null,
//             src:params?.src || null,
//             lyric:params?.lyric || null
//         }
//         songList.push(song)
//         setSongList(songList);
//     }
// }
//
// export default MusicPlayer;

import React, {Component, createRef} from 'react';
import ProgressBar from "./components/ProgressBar";
import MusicInfo from "./components/MusicInfo";
import {MusicContainer} from "./style/MusicePlayer.css";
import Controls from "./components/Controls";
import MusicList from "./components/MusicList";
const PLAY_MODE = [
    "顺序播放",
    "单曲循环",
    "随机播放"
]
class MusicPlayer extends Component {
    constructor(props) {
        super(props);
        this.au = new Audio();
        this.state={
            songList:[],
            nowSong:-1,
            currentTime:0,
            duration:0,
            mode:"顺序播放",
            volume:0.5,
            continued:true,
            playing:false,
            played:false,
        }
        this._songList=[]//播放队列
        this._nowSong=-1;//当前播放歌曲的索引
        this._mode="顺序播放";//播放模式
        this._volume=0.5//音量
        this._played=false//是否已经开始播放
        this._playing=false//是否正在播放
        this._continued=true//是否连续播放

        this.au.addEventListener("timeupdate",(e)=>{
            this.setState({
                currentTime:this.au.currentTime,
            })
        })
        this.au.addEventListener("durationchange",()=>{
            this.setState({
                duration:this.au.duration,
            })
        })
        this.au.addEventListener("volumechange",()=>{
            this.setState({
                volume:this.au.volume
            })
        })
        // this.au.addEventListener("loadeddata",()=> this._played=true)
        this.au.addEventListener("ended",()=>{
            console.log("ended")
            this._played = false;
            this._playing = false;
            this.setState({played:this._played,playing:this._playing})
            this._continued && this.next()
        })
        this.au.addEventListener("playing",()=>{
            this._played = true;
            this._playing = true;
            this.setState({played:this._played,playing:this._playing})
        })
        this.au.addEventListener("pause",()=>{
            this._playing = false;
            this.setState({playing:this._playing});
        })
        this.musicPlayerRef = createRef()

    }
    componentDidMount() {
        this.setVolume(0.5);
    }
    render() {
        return (
            <MusicContainer ref={this.musicPlayerRef}>
                <MusicInfo
                    imgUrl={this.getNowSong().song?.imgUrl}
                    title={this.getNowSong().song?.title}
                    artists={this.getNowSong().song?.artists}
                    playing={this.state.playing}
                    played={this.state.played}/>
                <Controls musicPlayer={this}/>
                <ProgressBar progress={this.getProgress()} setprogress={this.setProgress.bind(this)}/>
                <MusicList musicPlayer={this}/>

            </MusicContainer>
        );
    }
    play(){
        if(this._songList.length===0) return;
        if(this._nowSong===-1){
            //nowSong没指向时，尝试播放
            this.next()
            return;
        };
        if(isNaN(this.au.duration)){
            //如果当前没有歌曲资源被载入，就尝试载入资源
            this.load()
        }
        if(0<=this._nowSong && this._nowSong<this._songList.length){
            this.au.play()
                .then(r=>console.log(r))
                .catch(e=>this.stop())
        }
    }
    pause(){
        this.au.pause()
    }
    stop(){
        this.pause();
        this._nowSong = -1;
        this._playing = false;
        this._played = false;
        this.au.src="";
        this.au.load();
        this.setState({
            nowSong:this._nowSong,
            playing:this._playing,
            played:this._played,
            continued:this._continued,
        })
        this.forceUpdate();
    }
    load(){
        this.au.src = this.getNowSong().song?.src
        this.au.load()
    }
    next(){
        this.setNowSong();
        this.load();
        this.play();
    }
    prev(){
        let prevIndex = (this._songList.length+this._nowSong-1)%this._songList.length
        this.setNowSong(prevIndex);
        this.load();
        this.play();
    }

    getNowSong(){
        return {
            index:this._nowSong,
            song:this._songList[this._nowSong]
        }
    }
    setNowSong(index){
        if(this._songList.length===0){
            this._nowSong = -1;
            return this.getNowSong();
        }
        index = Number(index)
        index = index % this._songList.length;
        if(!isNaN(index)){
            if(-1<=index && index<this._songList.length) this._nowSong = index;
            else throw new Error("越界错误")
        }
        else {
            switch (this._mode) {
                case"顺序播放":{
                    this._nowSong = (this._nowSong+1)%this._songList.length;
                    console.log()
                    break;
                }
                case"单曲循环":{
                    break;
                }
                case"随机播放":{
                    this._nowSong = Math.floor(Math.random()*this._songList.length)
                    break;
                }
                default:{
                    console.error("播放模式不在预设中")
                    break;
                }
            }
        }
        console.log(this.state.nowSong,this._nowSong)
        this.setState({
            nowSong:this._nowSong
        })
        return this.getNowSong();
    }

    getMode(){
        return this.state.mode
    }
    setMode(mode){
        if(PLAY_MODE.includes(mode)){
            this._mode = mode
            this.setState(()=>({mode:this._mode}))
        }
        else {
            throw new Error("播放器无该播放模式")
        }

    }
    nextMode(){
        let nextModeIndex = (PLAY_MODE.indexOf(this._mode)+1)%PLAY_MODE.length
        this.setMode(PLAY_MODE[nextModeIndex]);
    }
    setCurrentTime(now){
        now = Number(now);
        if(isNaN(now)) throw new Error("now参数非法")
        if(now<0 || this.au.duration<now) throw new Error("[越界错误]：被设置的时间值超出时间轴范围");
        this.au.currentTime = now;
        this.setState({currentTime:this.au.currentTime})
    }

    getVolume(){
        return this.au.volume
    }
    setVolume(volume){
        volume = Number(volume);
        if(0<=volume && volume<=1){
            this.au.volume = volume;
            return volume;
        }
        else throw new Error("[范围错误]:音量应该为范围在[0,1]的浮点小数，比如,0.114514")
    }

    getProgress(){
        return this.au.currentTime/this.au.duration;
    }
    setProgress(progress){
        if(isNaN(progress) || isNaN(this.au.duration)){
            this.setCurrentTime(0)
            return -1;
        }
        if(0<=progress && progress<=1){
            this.setCurrentTime(this.au.duration*progress)
            return progress;
        }
        else throw new Error("[范围错误]:播放比例应该为范围在[0,1]的浮点小数，比如,0.114514")
    }


    addSong(params){
        let song = {
            key:(params?.id || 0) +  Math.floor(Math.random()*100000),
            id:params?.id || null,
            title:params?.title || null,
            artists:params?.artists || null,
            imgUrl:params?.imgUrl || null,
            src:params?.src || null,
            lyric:params?.lyric || null,
            metadata:params?.metadata || null,
        }
        this._songList.push(song)
        this.setState({
            songList:this._songList
        })
        return this._songList.length-1;
    }
    clearList(){
        this.stop();
        this._songList = [];
        this.setState({
            songList: this._songList
        })
    }
    getList(){
        return this.state.songList
    }
    playByIndex(index){
        index = Number(index)
        if(!isNaN(index)){//index参数有效则切换新歌索引
            this.stop()
            this.setNowSong(index);
            this.forceUpdate();
        }
        this.play();
    }
    deleteByIndex(index){
        let shouldNext = this._nowSong === index;
        this._songList.splice(index,1);
        if(index<this._nowSong)this.setNowSong(this._nowSong-1);//如果被删歌曲的索引比当前正在播放歌曲的索引要小，则正在播放歌曲的索引-1;
        if(shouldNext){
            this.stop()
            this.playByIndex(index);
        }
        this.setState({songList:this._songList})
    }

    //
    // getApi(){
    //     return{
    //         play:this.play.bind(this),
    //         pause:this.pause.bind(this),
    //         next:this.next.bind(this),
    //
    //         getMode:this.getMode,
    //         setMode:this.setMode,
    //
    //         setProgress:this.setProgress.bind(this),
    //
    //         setVolume:this.setVolume.bind(this),
    //         getVolume:this.getVolume.bind(this),
    //
    //         addSong:this.addSong.bind(this),
    //         clearList:this.clearList.bind(this),
    //         getList:this.getList.bind(this),
    //     }
    // }

}


function exportInner(Comp){
    function Helper(props){
        const {forwardRef, ...rest} = props;
        return <Comp ref={forwardRef} {...rest}/>
    }
    return React.forwardRef((props,ref)=>{
        return <Helper {...props} forwrdRef={ref}/>
    })
}


export default MusicPlayer;